package helixoide.secondlife;

import helixoide.hxLog;
import helixoide.secondlife.devices.deviceManager;
import java.net.*;
import java.io.*;
import java.util.*;
import sun.net.httpserver.*;
//runs the http server which gets connections from sl
public class httpServerMain 
{
	public void init(deviceManager managment)
	{
		try
        {
			
			hxLog.write("HttpServer", "Http Server is initialising");
            com.sun.net.httpserver.HttpServer server = com.sun.net.httpserver.HttpServer.create(new InetSocketAddress(8080),12);
            server.createContext("/slserv/com/", new httpHandler(managment));//Not entirely sure if this should be made dynamic, such s being loaded from he config file
            server.setExecutor(null);
            server.start();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
		
	}
	public class httpHandler implements com.sun.net.httpserver.HttpHandler
	{
		private deviceManager theManagment;
		public httpHandler(deviceManager manage)
		{
			theManagment = manage;
			
		}
		public void handle(com.sun.net.httpserver.HttpExchange t) throws IOException 
		{
			InputStream is = t.getRequestBody();
	        BufferedReader in = new BufferedReader(new InputStreamReader(is));// .. read the request body
	        String inputLine;
	        String blah = "";
	        while((inputLine = in.readLine()) !=null)
	        {
	        	
	        	blah += (inputLine);
	        }
	        
	        in.close();
	        
	        this.theManagment.handle(blah);
	        String response = "command recieved";
	        t.sendResponseHeaders(200, response.length());
	        OutputStream os = t.getResponseBody();
	        os.write(response.getBytes());
	        os.close();
		}
	}

}
